package com.itbaizhan;

import java.io.*;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**blob类型操作测试*/
//创建表
/*CREATE table movie (movieid int(11) not null auto_increment,
		moviename VARCHAR(30) DEFAULT null,
		poster mediumblob ,
		primary key(movieid)
		)ENGINE = innodb DEFAULT charset = utf8;*/
public class BlobTest01 {
    /*向Movie 表中插入数据*/
    //表中的poster 是Blob类型 是二进制  所以要用IO流
    //用InputStream 代表Blob类型
    public void insertMovie(String moviename, InputStream is){
        Connection connection = null;
        PreparedStatement ps = null;
        try{
            connection = JdbcUtils.getConnection();
            ps=connection.prepareStatement("insert into movie values(default,?,?)");
            //绑定数据
            ps.setString(1,"moviename");
            ps.setBlob(2,is);
            //执行语句
            ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResource(ps,connection);
        }
    }

    //获取Blob类型的信息
    //根据影片ID查询影片信息
    //取到整条数据的结果，再细分类型，取Blob
    public void selectMovieById(int movieid){
        Connection connection =null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try{
            connection = JdbcUtils.getConnection();
            ps = connection.prepareStatement("select * from movie where movieid = ?");
            //绑定参数
            ps.setInt(1,movieid);
            //执行语句
           resultSet = ps.executeQuery();
           while (resultSet.next()){
               int id = resultSet.getInt("movieid");
               String moviename = resultSet.getString("moviename");
               //获取Blob对象，可以操作Blob，并不是得到数据
               Blob blob = resultSet.getBlob("poster");
               //创建输入流
               InputStream is = blob.getBinaryStream();
               //创建输出流
               OutputStream os = new FileOutputStream(id+"_"+moviename+".jpg");
               byte[] buff = new byte[1024];
               int len;
               while ((len = is.read(buff)) != -1){
                   os.write(buff,0,len);
               }
               os.flush();
               os.close();
               is.close();
           }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResource(resultSet,ps,connection);
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        BlobTest01 bt = new BlobTest01();
        //创建输入流，指定文件
        InputStream is = new FileInputStream("e:/picture/1002.jpg");
        bt.insertMovie("端砚",is);
    }
}
